<template>
  <div>
    <div style="border: 1px solid #ccc">
      <Toolbar
          style="border-bottom: 1px solid #ccc;"
          :editor="editorRef"
          :defaultConfig="toolbarConfig"
          :mode="mode"
      />
    </div>
    <Editor
        style="overflow-y: hidden;border: 1px solid #ccc;"
        v-model="valueHtml"
        :defaultConfig="editorConfig"
        :mode="mode"
        @onCreated="handleCreated"
    />
  </div>
</template>

<script>
import '@wangeditor/editor/dist/css/style.css'; // 引入 css
import { onBeforeUnmount, ref, shallowRef, onMounted, watch } from 'vue';
import { Editor, Toolbar } from '@wangeditor/editor-for-vue';
import { mapState, useStore } from 'vuex';

export default {
  components: { Editor, Toolbar },
  computed: {
    ...mapState('CreateProject', ['project'])
  },
  setup() {
    const store = useStore();

    // 编辑器实例，必须用 shallowRef
    const editorRef = shallowRef();

    // 内容 HTML
    const valueHtml = ref('<p>hello</p>');

    // 模拟 ajax 异步获取内容
    onMounted(() => {
      setTimeout(() => {
        valueHtml.value = '<p>请输入内容...</p>';
      }, 1500);
    });

    // 自定义防抖函数
    const debounce = (func, wait) => {
      let timeout = null;
      const debounced = function(...args) {
        const context = this;
        if (timeout) clearTimeout(timeout);
        timeout = setTimeout(() => func.apply(context, args), wait);
      };
      return debounced;
    };

    // 创建一个防抖函数来更新 Vuex 中的 project.content
    const updateProjectContent = (newHtml) => {
      store.commit('CreateProject/updateProjectContent', newHtml);
    };

    const updateProjectContentDebounced = debounce(updateProjectContent, 2000); // 2000 毫秒的防抖间隔

    // 监听 valueHtml 的变化，并使用防抖函数更新 Vuex 中的 project.content
    watch(valueHtml, (newHtml) => {
      updateProjectContentDebounced(newHtml);
    });

    const toolbarConfig = {};
    const editorConfig = { placeholder: '请输入内容...' };

    // 组件销毁时，也及时销毁编辑器
    onBeforeUnmount(() => {
      const editor = editorRef.value;
      if (editor == null) return;
      editor.destroy();
    });

    const handleCreated = (editor) => {
      editorRef.value = editor; // 记录 editor 实例，重要！
    };

    const insertText = () => {
      const editor = editorRef.value; // 获取 editor ，必须等待它渲染完之后
      if (editor == null) return;
      editor.insertText('hello world'); // 执行 editor API
    };

    return {
      editorRef,
      valueHtml,
      mode: 'default', // 或 'simple'
      toolbarConfig,
      editorConfig,
      handleCreated,
      insertText,
    };
  },
};
</script>

<style>

</style>